package com.bt.lms.ui.action.teaching.plan;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.TeachingPlanBizTypeConstant;
import com.bt.lms.entity.TeachingPlanBasicInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.ui.page.common.action.pageteaching.TeachingPlanLabAction;
import com.bt.lms.ui.page.teaching.plan.PageList;
import com.bt.lms.ui.page.teaching.plan.PageSetTeachingPlanBasicInfo;
import com.bt.lms.ui.page.teaching.plan.PageTeachingPlanBasicInfoList;
import com.bt.lms.ui.page.teaching.plan.vo.AddTeachingSetVo;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import org.apache.commons.beanutils.BeanUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;

/**
 * 教学计划
 * 新增教学计划
 * 保存并返回按钮事件
 */
public class LSetTeachingPlanSaveBtnAction implements EventHandler<ActionEvent> {

    /**
     * 新增教学计划基本信息
     */
    private PageSetTeachingPlanBasicInfo plan;

    private String errors;


    @Override
    public void handle(ActionEvent event) {

        //1、获取用户输入
        AddTeachingSetVo addTeachingSetVo = getInParams();
        //2、验证用户输入
        String validateMsg = validateInParam(addTeachingSetVo);


        //3、组包(根据自定义的网络消息协议)
        byte[] msgByte;
        if (null == validateMsg) {
            //验证通过
            msgByte = handle2ReqMsgPacket(addTeachingSetVo);
        } else {

            //提示，程序终止
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(errors);
            alert.show();
            return;
        }


        //4.组网
        Socket socket = getNet();

        //5.发送消息
        boolean flag = sendReqMsgPacket(socket, msgByte);

        if (flag) {
            //要秀的界面
            PageList pageList = new PageList();
            Pane pane = TeachingPlanLabAction.pageSkipInfo.getPane();
            Integer index = TeachingPlanLabAction.pageSkipInfo.getIndex();
            pane.getChildren().set(index, pageList);
        }

    }

    /**
     * 发送消息
     * @param socket  网
     * @param msgByte  数组
     * @return 是否成功
     */
    private boolean sendReqMsgPacket(Socket socket, byte[] msgByte) {

        try {
            OutputStream out= socket.getOutputStream();
            out.write(msgByte);
            out.flush();

            byte[]  buffer = new byte[1024];
            InputStream in = socket.getInputStream();
            in.read(buffer);
            in.close();

            out.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return false;
    }


    /**
     * 4、组网
     * @return
     */
    private Socket getNet(){

        String serverip = "127.0.0.1";
        int  port = 8888;
        Socket socket = null;
        try {
            socket = new Socket(serverip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return socket;
    }

    /**
     *3、 组包
     * @param addTeachingSetVo  vo
     * @return  数组
     */
    private byte[] handle2ReqMsgPacket(AddTeachingSetVo addTeachingSetVo) {

        String date = null;
        TeachingPlanBasicInfo teachingPlanBasicInfo = new TeachingPlanBasicInfo();
        try {
            BeanUtils.copyProperties(teachingPlanBasicInfo,addTeachingSetVo);
            date = JSON.toJSONString(teachingPlanBasicInfo);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        ReqMsg reqMsg = new ReqMsg();
        reqMsg.setBizType(TeachingPlanBizTypeConstant.PLAN_TEACHING_ADD);
        reqMsg.setData(date);

        byte[] msgByte = reqMsg.toBytes();


        return msgByte;
    }


    /**
     * 2.验证用户的输入是否合法
     *
     * @param addTeachingSetVo 用户输入的信息
     * @return 验证的结果信息
     */
    private String validateInParam(AddTeachingSetVo addTeachingSetVo) {


        errors = "";

        //计划编号
        String code = addTeachingSetVo.getCode();
        int length = code.length();
        if ("".equals(code)) {
            errors += "计划编号必须填写。" + "\r\n";
        } else if (length > 32) {
            errors += "编号字数不能超过32字" + "\r\n";
        }

        //教学计划名称
        String name = addTeachingSetVo.getName();
        int nameLength = name.length();
        if (name.equals("")) {
            errors += "教学计划名称必须填写" + "\r\n";
        } else if (nameLength > 32) {
            errors += "教学计划名称不能超过32字" + "\r\n";
        }


        //学制
        String lengthOfSchoolingText = addTeachingSetVo.getLengthOfSchoolingText();

        if (lengthOfSchoolingText.equals("")) {
            errors += "学制不能为空" + "\r\n";
        } else {

            Integer textInt = null;

            try {
                textInt = Integer.parseInt(lengthOfSchoolingText);

                //学制限选项
                Integer lengthOfSchooling = addTeachingSetVo.getLengthOfSchooling();
                if (lengthOfSchooling == 1 && textInt > 4) {
                    errors += "学制最高4年。" + "\r\n";
                } else if (lengthOfSchooling == 2 && textInt > 48) {
                    errors += "学制最高48个月。" + "\r\n";
                } else if (lengthOfSchooling == 3 && textInt > 35040) {
                    errors += "学制最高35040个学时。" + "\r\n";
                }

            } catch (NumberFormatException e) {
                errors += "学制请填写数字" + "\r\n";
            }


        }


        //可重修次数
        String numberOfRepairableTimes = addTeachingSetVo.getNumberOfRepairableTimes();
        Integer schooling = null;
        try {
            schooling = Integer.parseInt(numberOfRepairableTimes);
            if (schooling > 3) {
                errors = "可重修次数不能超过3次" + "\r\n";
            }


        } catch (NumberFormatException e) {
            errors += "可重修次数请填写数字" + "\r\n";
        }


        if (errors.equals("")) {
            errors = null;
        }

        return errors;
    }

    /**
     * 1.获取用户的输入
     *
     * @return 输入的信息
     */
    public AddTeachingSetVo getInParams() {

        TextField codeTF = (TextField) plan.lookup("#codeTF");//计划编号
        TextField nameTF = (TextField) plan.lookup("#nameTF");//教学计划名称
        ComboBox belToCollegeCB = (ComboBox) plan.lookup("#belToCollegeCB");//所属的学习中心
        ComboBox belongToMajor = (ComboBox) plan.lookup("#belongToMajor");//所属专业
        ComboBox applyCB = (ComboBox) plan.lookup("#applyCB");//适合层次
        TextField lengthOfSchoolingTF = (TextField) plan.lookup("#lengthOfSchoolingTF");//学制
        ComboBox lengthOfSchoolingCB = (ComboBox) plan.lookup("#lengthOfSchoolingCB");//学制限选项
        TextField numberOfRepairableTimesTF = (TextField) plan.lookup("#numberOfRepairableTimesTF");//可重修次数


        //封装成VO对象
        AddTeachingSetVo addTeachingSetVo = new AddTeachingSetVo();

        String codeStr = codeTF.getText().trim();//去掉无效空格
        addTeachingSetVo.setCode(codeStr);//计划编号

        String nameStr = nameTF.getText().trim();//教学计划名称
        addTeachingSetVo.setName(nameStr);

        String belongToMajorValue = (String) belongToMajor.getValue();//所属专业
        Integer belongTMValue = -1;
        switch (belongToMajorValue) {
            case "java":
                belongTMValue = 1;
                break;
            case "c++":
                belongTMValue = 2;
                break;
            case "c":
                belongTMValue = 3;
                break;
        }
        addTeachingSetVo.setLearningCenter(belongTMValue);

        String belToCollegeCBValue = (String) belToCollegeCB.getValue();//所属院校
        Integer belToCollegeValue = -1;
        switch (belToCollegeCBValue) {

            case "北京师范大学":
                belToCollegeValue = 1;
                break;
            case "北京大学":
                belToCollegeValue = 2;
                break;
        }
        addTeachingSetVo.setLearningCenter(belToCollegeValue);

        String applyCBValue = (String) applyCB.getValue();//适合层次
        Integer applyValue = -1;
        switch (applyCBValue) {


            case "高中":
                applyValue = 1;
                break;
            case "大专":
                applyValue = 2;
                break;
            case "本科":
                applyValue = 3;
                break;
        }
        addTeachingSetVo.setApplyLevel(applyValue);


        String lengthOfSchoolingTFStr = lengthOfSchoolingTF.getText().trim();//学制
        addTeachingSetVo.setLengthOfSchoolingText(lengthOfSchoolingTFStr);
        String lengthOfSchoolingCBValue = (String) lengthOfSchoolingCB.getValue();//学制限选项
        int lengthOSV = -1;
        switch (lengthOfSchoolingCBValue) {
            case "年":
                lengthOSV = 1;
                break;
            case "月":
                lengthOSV = 2;
                break;
            case "学时":
                lengthOSV = 3;
                break;

        }
        addTeachingSetVo.setLengthOfSchooling(lengthOSV);

        String numberOfRepairableTimesStr = numberOfRepairableTimesTF.getText().trim();//可重修次数
        addTeachingSetVo.setNumberOfRepairableTimes(numberOfRepairableTimesStr);


        return addTeachingSetVo;
    }


    public PageSetTeachingPlanBasicInfo getPlan(PageSetTeachingPlanBasicInfo pageSetTeachingPlanBasicInfo) {
        return plan;
    }

    public void setPlan(PageSetTeachingPlanBasicInfo plan) {
        this.plan = plan;
    }

    /**
     * 合并数组
     */
    public static byte[] mergeByte(byte[]... bytes) {

        int length = 0;
        for (byte[] a : bytes) {
            length += a.length;
        }
        byte[] general = new byte[length];
        int targetLocation = 0;
        for (byte[] a : bytes) {
            System.arraycopy(a, 0, general, targetLocation, a.length);
            targetLocation += a.length;
        }


        return general;
    }
}
